<template>
  <!-- :before-close="handleClose" -->
  <Dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    :max-height="maxHeight"
    :width="width"
    append-to-body
    style="padding-bottom: 0px !important"
  >
    <el-container>
      <el-aside class="aside">
        <div class="flex h-[calc(100%-40px)]">
          <el-scrollbar :max-height="maxHeight" class="!w-260px">
            <div
              class="payment-item"
              :class="{ 'payment-item-active': nowPaymentIndex == index || channel.payStatus }"
              v-for="(channel, index) in state.payMethods.items"
              :key="channel.id"
              @click="selectPayMent(index)"
            >
              <div class="flex items-center">
                <div class="mx-10px">
                  <el-image :src="channel.picUrl" class="icon" />
                </div>
                <div class="!w-full">
                  <el-text truncated class="custom-text-16 ml-10px w-200px">
                    {{ channel.assetsTitle }}</el-text
                  >
                  <div class="flex !w-full items-center">
                    <el-text class="custom-text-16 mt-10">
                      <span class="c-[var(--el-color-primary)]">{{ channel.leftStatus }}</span>
                    </el-text>
                    <el-text>
                      <Icon
                        icon="ep:view"
                        @click.stop="handleChange(channel)"
                        class="ml-10px c-[var(--el-color-primary)]"
                      />
                    </el-text>
                  </div>
                </div>
              </div>

              <div class="virtual_san" v-if="channel.payStatus"></div>
              <div class="virtual_dui custom-text-18" v-if="channel.payStatus">✓</div>
            </div>
          </el-scrollbar>
        </div>
      </el-aside>

      <el-main class="main">
        <el-row class="payment-info">
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
            <div class="text-center">
              <div class="custom-text-24 c-[var(--el-color-primary)]!"
                >￥{{ fenToYuan(state.orderInfo.price.totalPrice) }}</div
              >
              <div class="custom-text-18">订单金额</div>
            </div>
          </el-col>
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
            <div class="text-center">
              <div class="custom-text-24 c-[var(--el-color-primary)]!"
                >￥{{ fenToYuan(state.payMethods.totalPayPrice) }}</div
              >
              <div class="custom-text-18">本次抵扣</div>
            </div>
          </el-col>
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
            <div class="text-center">
              <div class="custom-text-24 c-[var(--el-color-primary)]!"
                >￥{{ fenToYuan(state.orderInfo.price.payPrice) }}</div
              >
              <div class="custom-text-18">待支付金额</div>
            </div>
          </el-col>
        </el-row>

        <div class="mt-20px">
          <el-input
            v-model="nowPayment.usePayBalance"
            :disabled="nowPayment.payStatus"
            class="payment-input custom-text-44"
            ref="inputRef"
            :formatter="(value: any) => verifyNumberIntegerAndFloat(value)"
          >
            <template #prepend>
              <div class="flex items-center">
                <el-image :src="collection" class="collection-icon" />
                <span class="custom-text-22 ml-5px"> 折算金额</span>
              </div>
            </template>
          </el-input>
        </div>
        <el-divider border-style="dashed" class="!m-y-10px" />
        <div class="flex justify-between w-100% items-center mt-10px">
          <div class="custom-text-20" style="color: #707070">
            &nbsp; 可折算金额: ￥{{ fenToYuan(nowPayment.usableBalance) }}
          </div>
          <div class="flex">
            <el-text type="primary" class="custom-text-18 mr-5px!" @click="onHandleCancel">
              取消使用
            </el-text>
          </div>
        </div>

        <div class="mt-10px">
          <DigitKeyboard
            ref="DigitKeyboardRef"
            @on-change="onInputChange"
            @on-confirm="onConfirm"
            @on-cancel="onHandleCancel"
            :disabled="nowPayment.payStatus"
            :input="nowPayment.usePayBalance"
          />
        </div>
      </el-main>
    </el-container>
    <template #footer v-if="slots.footer">
      <slot name="footer"></slot>
    </template>
  </Dialog>
  <ReplaceForm ref="replaceFormRef" />
</template>
<script setup lang="ts">
import { ref, useSlots, watch } from 'vue'
import collection from '@/assets/svgs/collection.svg'

import { fenToYuan, yuanToFen } from '@/utils'
import ReplaceForm from '@/views/shop/sales/components/ReplaceForm.vue' //下单表单

import _ from 'lodash'

import DigitKeyboard from '@/views/shop/components/paymentDialog/digitKeyBoard.vue'
const slots = useSlots()
import { propTypes } from '@/utils/propTypes'
const props = defineProps({
  orderInfo: propTypes.object, //订单信息
  paymentMap: propTypes.array
})

// 选择商品
const replaceFormRef = ref()

const handleChange = (item) => {
  console.log(item)
  replaceFormRef.value.open(item)
}

// 检测支付环境
const state = reactive({
  orderInfo: computed(() => {
    return props.orderInfo
  }), // 支付单信息
  payMethods: computed(() => {
    return props.paymentMap.find((ele: any) => {
      return ele.classify == nowPaymenthds.value.classify
    })
  }) as any, // 可选的支付方式
  payment: '', // 选中的支付方式
  payOrderList: [] as any, //当前支付方式的支付流水号
  activeName: '' //当前选中的支付方式
})

const nowPaymenthds = ref() //当前使用的资产

const DigitKeyboardRef = ref()
const onInputChange = (input: any) => {
  nowPayment.value.usePayBalance = input
} //输入发生变化时
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('选择资产') // 弹窗的标题
const width = ref('785px') //宽度
const maxHeight = ref('545px')
// 选择支付方式
const emit = defineEmits(['handleUseAssetsPay'])
// 监听支付方式的变化
watch(
  () => props.paymentMap,
  () => {
    if (nowPaymentIndex.value == undefined) {
      return
    }

    nowPayment.value = state.payMethods.items[nowPaymentIndex.value]
    if (nowPayment.value.payStatus) {
      nowPayment.value.usePayBalance = fenToYuan(nowPayment.value.paybalance)
    } else {
      nowPayment.value.usePayBalance = ''
    }
    setKeyBoardLayout()
  }
)
const nowPayment = ref<any>({})

const nowPaymentIndex = ref<any>() //当前支付方式的下标
const inputRef = ref()
const selectPayMent = (index: any) => {
  nowPaymentIndex.value = index
  let item = state.payMethods.items[nowPaymentIndex.value]

  nowPayment.value = item
  setKeyBoardLayout()
}

const onHandleCancel = () => {
  let item = state.payMethods.items[nowPaymentIndex.value]
  item.payStatus = false

  emit('handleUseAssetsPay', item, nowPaymenthds.value.classify)
}

/** 打开弹窗 */

const open = async (payMethods: any) => {
  console.log(payMethods)
  dialogVisible.value = true
  nowPaymenthds.value = payMethods
  await setNowPayment()
}
const setNowPayment = () => {
  let selectPayMentIndexs = [] as any
  state.payMethods.items.forEach((element, index) => {
    if (element.payStatus) {
      selectPayMentIndexs.push(index)
    }
  })
  console.log(selectPayMentIndexs)

  if (selectPayMentIndexs.length == 0) {
    nowPayment.value = {}
    // selectPayMent(0)
  } else {
    nowPaymentIndex.value = selectPayMentIndexs[0]
    nowPayment.value = state.payMethods.items[nowPaymentIndex.value]
    state.activeName = nowPayment.value.assetsTitle
    nowPayment.value.usePayBalance = fenToYuan(nowPayment.value.paybalance)
  }
} //设置当前选中的支付方式
const close = async () => {
  dialogVisible.value = false
}

defineExpose({ open, close }) // 提供 open 方法，用于打开弹窗

const message = useMessage() // 消息弹窗
// import { ElMessageBox } from 'element-plus'
import { verifyNumberIntegerAndFloat } from '@/utils/formatter'
/** 购物车信息 */

const onConfirm = async () => {
  if (!nowPayment.value.usePayBalance) {
    message.error('折算金额不能为空')
    return
  }

  nowPayment.value.paybalance = yuanToFen(nowPayment.value.usePayBalance)
  if (Number(nowPayment.value.paybalance) <= 0) {
    message.error('折算金额必须大于0')
    return
  }
  if (Number(nowPayment.value.paybalance) > Number(nowPayment.value.usableBalance)) {
    message.error('折算金额不得大于可折算金额')
    return
  }
  nowPayment.value.payStatus = true
  emit('handleUseAssetsPay', nowPayment.value, nowPaymenthds.value.classify)
} //确认当前支付方式

const setKeyBoardLayout = () => {
  if (nowPayment.value.payStatus) {
    setTimeout(() => {
      DigitKeyboardRef.value.setKeyBoardLayout('cancel')
    }, 100)
  } else {
    setTimeout(() => {
      DigitKeyboardRef.value.setKeyBoardLayout('default')
    }, 100)
  }
}
</script>
<style lang="scss" scoped>
.aside {
  width: 260px;
  display: flex;
  flex-direction: column;
}

.main {
  margin-left: 20px;
  width: 470px;
}

:deep(.el-main) {
  --el-main-padding: 0px !important;
  width: 470px;
}

.payment-item {
  width: 260px;
  height: 70px;
  margin-bottom: 10px;
  background: url('@/assets/imgs/payCashier/paymentBg.png') center no-repeat;
  background-size: 100% 100%;
  cursor: pointer;
  display: flex;
  align-items: center;

  .icon {
    width: 36px;
    height: 36px;
  }

  .virtual_san {
    display: none;
  }

  .virtual_dui {
    display: none;
  }

  &-active {
    background: url('@/assets/imgs/payCashier/paymentActive.png') center no-repeat;
    background-size: 100% 100%;
    position: relative;

    .virtual_san {
      display: block;
      position: absolute;
      bottom: 0;
      right: 0;
      width: 0;
      height: 0;
      border-bottom: 35px solid var(--el-color-primary);
      border-left: 35px solid transparent;
      border-bottom-right-radius: 5px;
    }

    .virtual_dui {
      display: block;

      position: absolute;
      bottom: -2px;
      right: 5px;
      color: #fff;
      font-family: system-ui;
    }
  }
}

// .payment-info {
//   width: 470px;
//   height: 85px;
//   display: flex;
//   flex-direction: row;
//   justify-content: space-between;
//   align-items: center;
//   background-color: var(--app-content-bg-color) !important;
//   border-radius: 5px;

//   &-item {
//     width: 117.5px;
//     text-align: center;
//   }
// }

.payment-input {
  width: 470px;

  height: 60px;

  :deep(.el-input-group__prepend) {
    background: var(--el-color-primary);
    color: #fff;
    padding: 0 10px;
    box-shadow: none;
  }

  :deep(.el-input__inner) {
    --el-input-inner-height: 48px;
  }
  :deep(.el-input-group__append) {
    background: var(--el-color-primary);
    color: #fff;
    padding: 0 10px;
    box-shadow: none;
  }
}

:deep(.el-divider--horizontal) {
  margin: 20px 0 13px 0;
}

.collection-icon {
  width: 24px;
  height: 24px;
}
</style>
